//
//  DownloadModule.m
//  XYLib
//
//  Created by XYLib on 6/9/18.
//  Copyright © 2018年 XYLib. All rights reserved.
//

#import "DownloadModule.h"

@interface DownloadModule() <NSURLSessionDownloadDelegate>
{
    NSString* fileName;
}

@property(nonatomic,copy)WXModuleCallback errorCallBack;
@property(nonatomic,copy)WXModuleKeepAliveCallback messageCallBack;

@property (nonatomic,strong)NSURLSessionDownloadTask *downloadTask; /** 下载任务 */

@property (nonatomic,strong)NSData *resumeData; /** 下载的数据信息 */

@property (nonatomic,strong)NSURLSession *URLSession; /** 下载的会话 */
@end

@implementation DownloadModule
WX_EXPORT_METHOD(@selector(download:callback:))
WX_EXPORT_METHOD(@selector(start))
WX_EXPORT_METHOD(@selector(stop))
WX_EXPORT_METHOD(@selector(cancel))
WX_EXPORT_METHOD(@selector(resume))
WX_EXPORT_METHOD(@selector(onmessage:))

-(void)download:(NSString*)strUrl callback:(WXModuleKeepAliveCallback)callback{
    NSURL* url = [NSURL URLWithString:strUrl];
    
    if (nil == url) {
        return;
    }
    
    if (nil == self.URLSession) {
        NSURLSessionConfiguration* defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 创建会话
        self.URLSession = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    
    fileName = [strUrl lastPathComponent];
    // 通过会话在确定的URL上创建下载任务
    if (url) {
        self.downloadTask = [self.URLSession downloadTaskWithURL:url];
    }
    self.messageCallBack = callback;
    [self start];
}

// 开始下载
-(void) start{
    if (self.downloadTask) {
        // 启动任务
        [self.downloadTask resume];
    }
}

// 停止下载
-(void) stop{
    if (self.downloadTask) {
        //暂停任务
        [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData){
            NSLog(@"resumeData = %tu",resumeData.length);
            // 暂停的时候，我们需要释放下载任务、保存下载数据
            self.downloadTask = nil;
            self.resumeData = resumeData;
        }];
    }
}

-(void)cancel{
    if (self.downloadTask) {
        [self.downloadTask cancel];
        self.downloadTask = nil;
    }
}
// 继续下载
- (void)resume {
    if (self.resumeData) {
        NSURLSessionDownloadTask* downloadTask = [self.URLSession downloadTaskWithResumeData:self.resumeData];
        [downloadTask resume];
        if (self.downloadTask) {
            [self.downloadTask cancel];
            self.downloadTask = nil;
        }
        self.downloadTask = downloadTask;
    }
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
#ifdef DEBUG
    NSLog(@"rd %lld",100 * totalBytesWritten / totalBytesExpectedToWrite);
#endif
    if (self.messageCallBack) {
        self.messageCallBack(@{@"total":@(totalBytesExpectedToWrite),@"bytes":@(totalBytesWritten)},true);
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //    NSString* fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    if (nil == fileName || [@"" isEqualToString:fileName]) {
        fileName = [location.absoluteString lastPathComponent];
    }
    NSString* fullPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:fullPath isDirectory:NULL]) {
        [fileManager removeItemAtURL:[NSURL fileURLWithPath:fullPath]  error:NULL];
    }
    BOOL  moved = [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
    if (self.messageCallBack) {
        if (moved) {
            self.messageCallBack(@{@"result":@"success",@"path":fullPath},false);
        }else{
            [[NSFileManager defaultManager] removeItemAtURL:location error:nil];
            self.messageCallBack(@{@"result":@"error"},false);
        }
    }
    //    NSLog(@"rd %@",fullPath);
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (self.messageCallBack) {
        if(error){
            self.messageCallBack(@{@"result":@"error",@"code":@(error.code)},false);
        }
    }
}

- (void)onmessage:(WXModuleKeepAliveCallback)callback
{
//    self.messageCallBack = callback;
}
@end

